package com.jmgd.cjlx.aop;

import com.jmgd.cjlx.config.GlobalExceptionHandler;
import com.jmgd.cjlx.controller.DzController;
import com.jmgd.cjlx.dao.TLxExceptionLogMapper;
import com.jmgd.cjlx.entity.TLxExceptionLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class GlobalExceptionAspect {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionAspect.class);


    @Autowired
    TLxExceptionLogMapper tLxExceptionLogMapper;


    @AfterThrowing(pointcut = "execution(* com.jmgd.cjlx.service.impl.DzGyServiceImpl.callBack(..)) || execution(* com.jmgd.cjlx.service.impl.JztServiceImpl.callBack(..))",
            throwing = "exception")
    public void handleServiceException(JoinPoint joinPoint, Exception exception) {
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();


        // 打印异常信息和参数
        logger.info("Method " + methodName + " threw an exception: " + exception.getMessage());
        StringBuilder argument = new StringBuilder();
        for (Object arg : args) {
            logger.info("Argument: " + arg);
            argument.append(arg);
        }

        StackTraceElement[] stackTrace = exception.getStackTrace();


        if (stackTrace.length > 0) {
            StackTraceElement element = stackTrace[0];
            String className = element.getClassName();
            int lineNumber = element.getLineNumber();

            TLxExceptionLog tLxExceptionLog = new TLxExceptionLog();
            tLxExceptionLog.setArgument(argument.toString());
            tLxExceptionLog.setCreatedate(new Date());
            tLxExceptionLog.setExceptiondata(exception.getMessage()+"类："+className+"报错行数："+lineNumber);
            tLxExceptionLog.setMethod(methodName);
            tLxExceptionLogMapper.insert(tLxExceptionLog);
        }



        // 这里可以调用全局异常处理逻辑
        GlobalExceptionHandler handler = new GlobalExceptionHandler();
        handler.handleException(exception);
    }
}

